// utils/util.js
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

// API请求封装
const request = (url, options = {}) => {
  const app = getApp()
  const baseUrl = app.globalData.baseUrl
  
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        'Authorization': wx.getStorageSync('token') || '',
        ...options.header
      },
      success: (res) => {
        if (res.statusCode === 200) {
          if (res.data.code === 0) {
            resolve(res.data.data)
          } else {
            // 检查是否是 Token 失效错误
            const message = res.data.message || ''
            if (message.includes('Token验证失败') || message.includes('Token已失效') || message.includes('登录已过期')) {
              // 清除本地存储的用户信息
              wx.removeStorageSync('userInfo')
              wx.removeStorageSync('token')
              wx.removeStorageSync('sessionKey')
              if (app && app.globalData) {
                app.globalData.userInfo = null
                app.globalData.token = null
                app.globalData.sessionKey = null
              }
              
              // 静默跳转到登录页，不显示错误提示
              wx.reLaunch({
                url: '/pages/index/index'
              })
              reject(res.data)
            } else {
              // 其他错误正常显示提示
              wx.showToast({
                title: message || '请求失败',
                icon: 'none'
              })
              reject(res.data)
            }
          }
        } else {
          wx.showToast({
            title: '网络请求失败',
            icon: 'none'
          })
          reject(res)
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络连接失败',
          icon: 'none'
        })
        reject(err)
      }
    })
  })
}

// 显示加载提示
const showLoading = (title = '加载中...') => {
  wx.showLoading({
    title,
    mask: true
  })
}

// 隐藏加载提示
const hideLoading = () => {
  wx.hideLoading()
}

// 显示成功提示
const showSuccess = (title = '操作成功') => {
  wx.showToast({
    title,
    icon: 'success',
    duration: 2000
  })
}

// 显示错误提示
const showError = (title = '操作失败') => {
  wx.showToast({
    title,
    icon: 'none',
    duration: 2000
  })
}

// 确认对话框
const showConfirm = (content, title = '提示') => {
  return new Promise((resolve) => {
    wx.showModal({
      title,
      content,
      success: (res) => {
        resolve(res.confirm)
      }
    })
  })
}

// 选择图片
const chooseImage = (count = 1) => {
  return new Promise((resolve, reject) => {
    wx.chooseImage({
      count,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: resolve,
      fail: reject
    })
  })
}

// 上传文件
const uploadFile = (filePath, name = 'file') => {
  const app = getApp()
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: app.globalData.baseUrl + '/upload/file',
      filePath,
      name,
      header: {
        'Authorization': wx.getStorageSync('token') || ''
      },
      success: (res) => {
        try {
          const data = JSON.parse(res.data)
          console.log('文件上传响应:', data)
          if (data.code === 200 && data.data) {
            // 后端返回的是 {url: '...', key: '...'}
            resolve(data.data.url)
          } else {
            reject(new Error(data.message || '上传失败'))
          }
        } catch (e) {
          console.error('解析上传响应失败:', e)
          reject(e)
        }
      },
      fail: reject
    })
  })
}

// 格式化金额
const formatMoney = (amount) => {
  return (amount / 100).toFixed(2)
}

// 格式化日期
const formatDate = (date, format = 'YYYY-MM-DD') => {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hour = String(d.getHours()).padStart(2, '0')
  const minute = String(d.getMinutes()).padStart(2, '0')
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hour)
    .replace('mm', minute)
}

// 计算距离
const calculateDistance = (lat1, lng1, lat2, lng2) => {
  const R = 6371 // 地球半径（公里）
  const dLat = (lat2 - lat1) * Math.PI / 180
  const dLng = (lng2 - lng1) * Math.PI / 180
  const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
    Math.sin(dLng / 2) * Math.sin(dLng / 2)
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
  return R * c
}

module.exports = {
  formatTime,
  request,
  showLoading,
  hideLoading,
  showSuccess,
  showError,
  showConfirm,
  chooseImage,
  uploadFile,
  formatMoney,
  formatDate,
  calculateDistance
}